# 将序列分解为单独的变量
# 1. 有一个包含n个元素的序列，现在将它分解为n个单独的变量
p = (4, 5)
x, y = p
print(x)
print(y)

data = ["SHAWN", 26, 180.1, (2020, 10, 27)]
name, age, high, date = data
print(name)
print(age)
print(high)
print(date)

name, age, high, (year, mon, day) = data
print(name)
print(age)
print(high)
print(year)
print(mon)
print(day)

# 如果元素的数量不匹配，将会得到错误提示
'''
Traceback (most recent call last):
  File ".\sequence-item.py", line 24, in <module>
    x, y, z = p
ValueError: not enough values to unpack (expected 3, got 2)
'''
# x, y, z = p

# 只要对象是可以迭代的，那么就可以执行分解操作。字符串，列表，元祖，文件，迭代器，生成器
# 有时想要丢弃某些变量的值，可以选用一个用不到变量名，以此来作为要丢弃的值的名称
name, _, _, date = data
print(name)
print(date)

# 从任意长度的可迭代对象中分解元素
# 问题：需要从某个可迭代对象中分解出N个元素，但是这个可迭代的对象的长度可能大于N，就会导致出现“分解的值过多(too many values to unpack)”的异常
# 可以使用*args
record = ["Dave", "dave@example.com", "12345678901", "12345678902"]
name, email, *phone = record
print(name)
print(email)
print(phone)

records = [('foo', 1, 2), ('bar', 3), ('foo', 4, 5)]

def do_foo(x, y):
    print('foo', x, y)

def do_bar(x):
    print('bar', x)

for tag, *args in records:
    if tag == 'foo':
        do_foo(*args)
    elif tag == 'bar':
        do_bar(*args)

line = 'Shawn:26:shanghai:12345678901:a@qq.com'
name, *field, email = line.split(':')
print(name)
print(email)

# 演示忽略
data = ["SHAWN", 26, 180.1, (2020, 10, 27)]
name, *_, (*ig, day) = data
print(name)
print(day)

# 获取列表的表头和表尾
items = [1,2,3,4,5,6]
head, *mid, tail = items
print(head)
print(tail)